<template>
  <div class="login" v-if="showLogin == 'true'">
    <div class="logo">
      <img style="width: 33px; margin-right: 5px" src="../../assets/img/logo-login.png" />
      <span class="title">{{ systemName }}</span>
    </div>
    <div class="wrap">
      <div class="login-left"></div>
      <div class="login-right">
        <div class="login-form">
          <div>
            <h3 class="login-form-title" style="font-weight: normal">账号登录</h3>
          </div>
          <a-form-model ref="loginForm" :model="form" :rules="rules">
            <div class="alertDiv" v-show="alertShow">
              <a-icon type="close" @click="alertShow = false" />
              <a-alert type="error" :message="error" showIcon style="margin-bottom: 24px" />
            </div>
            <a-form-model-item prop="phone">
              <a-input autocomplete="autocomplete" size="large" placeholder="请输入手机号" v-model="form.phone">
                <a-icon slot="prefix" type="mobile" />
              </a-input>
            </a-form-model-item>
            <a-form-model-item prop="password">
              <a-input-password size="large" placeholder="请输入密码" autocomplete="autocomplete" v-model="form.password">
                <a-icon slot="prefix" type="lock" />
              </a-input-password>
            </a-form-model-item>
            <a-form-model-item prop="smsCode">
              <div style="display: flex;justify-content: space-between;">
                <a-input style="width: 58%; margin-right: 6px" size="large" placeholder="请输入手机短信验证码" autocomplete="autocomplete" v-model="form.smsCode">
                  <a-icon slot="prefix" type="check-circle" />
                </a-input>
                <a-button
                  type="primary"
                  size="large"
                  :disabled="isSend"
                  class="position-r smsBtn"
                  @click="coutDown()"
                  >{{ codeName }}</a-button
                >
                <!-- <img :src="codeImg" height="42" class="position-r cursorPoint" style="top: -2px" @click="getImgCode" /> -->
              </div>
            </a-form-model-item>
            <a-form-model-item prop="vercode" v-show="false">
              <a-input size="large" autocomplete="autocomplete" v-model="form.vercodeToken"></a-input>
            </a-form-model-item>
            <a-form-item>
              <a-button class="login-btn" v-show="this.tabname == 1" :loading="logging" size="large" @click="onSubmit('loginForm')" htmlType="submit" type="primary"
                >立即登录
              </a-button>
            </a-form-item>
          </a-form-model>
          <a-divider>您还可以使用以下方式登录</a-divider>
        <div style="text-align:center;">
          <a :href="szyUrl">
            <img style="width: 42px;" src="@/assets/img/szylogo.png" />
          </a>
        </div>
        </div>
      </div>
    </div>
    <!-- <div class="verify">
            <Vcode :show="isShow" @success="codeSuccess" @close="onClose" class="code"></Vcode>
        </div> -->
  </div>
  <!-- <span v-else>请稍等，请求登录中...</span> -->
</template>

<script>
// import Vcode from 'vue-puzzle-vcode';
import { getSms,loginSms, getRoutesConfig,getToken2 } from '@/services/user';
import { code } from '@/services/system';
import { setAuthorization } from '@/utils/request';
import { encrypt,getQueryParams } from '@/utils/util';
import { loadRoutes } from '@/utils/routerUtil';
import { mapMutations } from 'vuex';
import { setStore } from '@/utils/store';
// import { rule } from "@/utils/validateRules";
import { timeFix, sortMenu, sortPermission } from '@/utils/common';

export default {
  name: 'Login',
  components: {},
  data() {
    return {
      logging: false,
      isShow: false,
      alertShow: false,
      showLogin: process.env.VUE_APP_IS_DEFAULT_LOGIN, //true为默认登录页，false为直接深职院登录
      isSend: false,
      codeName: '获取验证码',
      totalTime: 30,
      timer: '',
      tabname: 1,
      url: '',
      error: '',
      form: {
        phone: '',
        password: '',
        smsCode: '',
        smsCodeToken: '',
      },
      rules: {
        phone: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
        smsCode: [
          { required: true, message: "验证码不能为空", trigger: "blur" },
        ],
      },
      codeImg: '',
      redirectUri: encodeURIComponent('https://nrsh.szpu.edu.cn/#/login'),
      szyUrl: '',
      clientId: '1176923326064746496'
    };
  },
  created() {
    console.log(this.showLogin);
    this.szyUrl = 'https://authserver.szpt.edu.cn/authserver/oauth2.0/authorize?response_type=code&client_id=' + this.clientId + '&redirect_uri=' + this.redirectUri + '&state=' + new Date().getTime();
    let code = getQueryParams(window.location.href)['code'];
    if(!code){
      //没code直接跳转深职院不显示登录页
      if(this.showLogin == 'false'){
        location.href = this.szyUrl;
      } else {
        this.form.phone = sessionStorage.getItem("loginName") || "";
      }
    } else{
      getToken2({ code }).then(this.afterSzyLogin)
    }
  },
  computed: {
    systemName() {
      return this.$store.state.setting.systemName;
    },
  },
  methods: {
    ...mapMutations('account', ['setUser', 'setPermissions', 'setRoles', 'setIconMap']),
    onClose() {
      this.isShow = false;
    },
    coutDown() {
      if (this.isSend) return;
      //获取验证码接口
      getSms({ phone: this.form.phone, type: "1" }).then((res) => {
        if (res.data.code == 0) {
          this.form.smsCodeToken = res.data.data.smsCodeToken;
          //如果有返回smsCode值 则自动填入
          if(res.data.data.smsCode){
              this.form.smsCode = res.data.data.smsCode
          }
          this.isSend = true;
          this.codeName = this.totalTime + "s后重新发送";
          this.timer = setInterval(() => {
            this.totalTime--;
            this.codeName = this.totalTime + "s后重新发送";
            if (this.totalTime < 0) {
              clearInterval(this.timer);
              this.codeName = "重新发送验证码";
              this.totalTime = 30;
              this.isSend = false;
            }
          }, 1000);
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    // 用户通过了验证
    // codeSuccess() {
    //   this.isShow = false; // 通过验证后，需要手动隐藏模态框
    //   this.logging = true;
    //   sessionStorage.setItem('v3.loginName', this.form.username);
    //   login(this.form.username, encrypt(this.form.password, 'rsnsrsnsrsnsrsns'), this.form.vercode, this.form.vercodeToken).then(this.afterLogin);
    // },
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          sessionStorage.setItem("admin.loginName", this.form.phone);
          loginSms(
            this.form.phone,
            encrypt(this.form.password, "rsnsrsnsrsnsrsns"),
            this.form.smsCode,
            this.form.smsCodeToken
          ).then(this.afterLogin);

        } else {
          return false;
        }
      });
    },
    getImgCode() {
      code().then((res) => {
        if (res.data.code == 0) {
          this.codeImg = res.data.data.imageBase64Data;
          this.form.vercodeToken = res.data.data.vercodeToken;
        } else {
          this.$message.error(res.data.message);
        }
      });
    },

    handLoginByWx() {
      const hrefUrl = 'http://' + window.location.host + '/#/WXLogin';
      if (!this.code) {
        this.url = `https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid=ww2ae8f1e379a63ab5&agentid=1000004&redirect_uri=${encodeURIComponent(hrefUrl)}&state=web_login`;
        // this.url=`https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid=ww2ae8f1e379a63ab5&agentid=1000004&redirect_uri=http%3A%2F%2Ftext.rsnschina.cn%2FWXLogin&state=web_login`
      }
      console.log(this.url);
    },

    afterLogin(res) {
      this.logging = false;
      const loginRes = res.data;
      if (loginRes.code == 0) {
        setAuthorization({ token: loginRes.data.accessToken });
        const userInfo = loginRes.data.userInfo;
        console.log(userInfo);
        //存入用户信息
        this.setUser(userInfo);
        if (!userInfo.pwdStatus || userInfo.overTime) {
          this.$router.push('resetPwd');
          return;
        }
        // 获取路由配置
        getRoutesConfig().then((res) => {
          console.log(res);
          if (res.data.data.length == 0) {
            this.$message.error('账号未授权');
            return false;
          }
          this.setIconMap(res.data.data);
          //整理菜单和权限数据
          let routesConfig = sortMenu(res.data.data);
          let permissionConfig = sortPermission(res.data.data);
          this.setPermissions(permissionConfig);
          loadRoutes(routesConfig);
          console.log(permissionConfig);
          let firstPage = routesConfig[0].children[0].children[0]
            ? `${routesConfig[0].children[0].router}/${routesConfig[0].children[0].children[0]}`
            : routesConfig[0].children[0].router;
          console.log(firstPage);
          setStore({
            name: 'firstMenuId_' + userInfo.id,
            content: firstPage,
          });
          this.$router.push(firstPage);
          this.$message.success(timeFix() + '，欢迎回来', 3);
        });
      } else {
        this.alertShow = true;
        this.error = loginRes.message;
        this.form.smsCode = '';
        this.showLogin = 'true';
      }
    },
    afterSzyLogin(res){
      this.logging = false;
      const loginRes = res.data;
      if (loginRes.code == 0) {
        setAuthorization({ token: loginRes.data.accessToken });
        const userInfo = loginRes.data.userInfo;
        //存入用户信息
        this.setUser(userInfo);
        // 获取路由配置
        getRoutesConfig().then((res) => {
          if (res.data.data.length == 0) {
            this.$message.error('账号未授权');
            return false;
          }
          this.setIconMap(res.data.data);
          //整理菜单和权限数据
          let routesConfig = sortMenu(res.data.data);
          let permissionConfig = sortPermission(res.data.data);
          this.setPermissions(permissionConfig);
          loadRoutes(routesConfig);
          let firstPage = routesConfig[0].children[0].children[0]
            ? `${routesConfig[0].children[0].router}/${routesConfig[0].children[0].children[0]}`
            : routesConfig[0].children[0].router;
          setStore({
            name: 'firstMenuId_' + userInfo.id,
            content: firstPage,
          });
          this.$router.push(firstPage);
          this.$message.success(timeFix() + '，欢迎回来', 3);
        });
      } else {
        this.$message.error(res.data.message);
        // location.href = this.szyUrl;
      }
    },
    tabsChange(val) {
      this.tabname = val;
    },
  },
};
</script>

<style lang="less" scoped>
@import '@/styles/variables';

.login {
  height: 100vh;
  display: flex;
  //background: url("../../assets/img/bg.png") no-repeat;
  background-size: 100% 100%;
  position: relative;
  font-size: 18px;

  .title {
    font-size: 24px;
    font-weight: 600 !important;
    color: #1e2a32;
    line-height: 33px;
  }
  .alertDiv {
    position: relative;
    i {
      position: absolute;
      top: 3px;
      right: 2px;
      z-index: 1;
    }
  }
  .logo {
    position: absolute;
    top: 14px;
    left: 24px;
    display: flex;
    align-items: center;
    font-weight: bold;
    z-index: 5;

    img {
      width: 24px;
    }
  }

  .wrap {
    width: 100%;
    height: 100%;
    //max-width: 1150px;
    //max-height: 620px;
    position: absolute;
    display: flex;
    // background: linear-gradient(180deg, #f7fbfb 0%, #edf6f5 100%);
    background: url('../../assets/img/login/login-bg.png') no-repeat center center;
    background-size: 100% 100%;
  }

  &-left,
  &-right {
    height: 100%;
    flex: 1;
  }

  &-left {
    width: 66%;
    display: flex;
    justify-content: center;
    align-items: center;

    &-bg {
      width: 760px;
      height: 540px;
      // background: url('../../assets/img/login/login-right-bg.png') no-repeat center center;
      background-size: 100% 100%;
    }
  }

  &-right {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  &-form {
    width: 500px;
    padding: 30px 50px;
    border-radius: 30px;
    box-shadow: 0px 4px 56px 0px rgba(178,64,64,0.06);
    border: 1px solid rgba(255, 255, 255, 0.4);
    background: rgba(255,255,255,0.26);
    /deep/.ant-divider-horizontal.ant-divider-with-text-center::before,
    /deep/.ant-divider-horizontal.ant-divider-with-text-center::after{
      border-color: #D8D8D8;
    }
    /deep/.ant-divider-inner-text{
      color: #b9b9b9;
    }
    &-title {
      font-size: 24px;
      font-weight: 600 !important;
      color: #1e2a32;
      line-height: 33px;
      margin-bottom: 50px;
      display: flex;
      align-items: center;
      position: relative;
      &::after{
        content: '';
        position: absolute;
        top: 46px;
        width: 40px;
        left: 0;
        border: 3px solid #D9232D;
        border-radius: 3px;
      }

    }
    /deep/.ant-input-prefix i{
      font-size: 16px;
      color: #D9232D;
    }
    .ant-form-item {
      margin-bottom: 30px;
    }
    /deep/ .ant-form-explain {
      margin-top: 8px;
    }
    .ant-input-affix-wrapper {
      height: 51px;
      box-shadow: none;
    }
    /deep/ .ant-input:hover,
    /deep/ .ant-input:active,
    /deep/ .ant-input:focus {
      border: 1px solid #539cf5 !important;
      -webkit-box-shadow: 0 0 0 !important;
      box-shadow: 0 0 0 !important;
    }
    /deep/ .ant-input {
      height: 100%;
      padding-left: 40px;
      font-size: inherit;
      border-radius: 8px;
      border: 1px solid #e3e5e8;
      background: rgba(255,255,255,0.38);
      border: 1px solid #ddd;
    }
    .smsBtn{
      width: 145px;
      height:50px;
      background: linear-gradient(179deg, #FF6868 0%, #DF3636 100%);
      border: 0;
      span{
        color: #fff;
      }
    }
    /deep/ .ant-btn-primary[disabled]{
        background-color:#f5f5f5;
        color: #fff;
    }
   .login-btn {
      width: 100%;
      margin-top: 24px;
      background: linear-gradient(179deg, #FF6868 0%, #DF3636 100%);
      border-radius: 38px;
      height: 56px;
      border: 0;
      font-size: 18px;
      font-weight: 600;
      line-height: 25px;
    }
  }
}
</style>
